<?php


namespace App\Logic;


use App\Base\AuthManager;
use App\Base\ErrCode;
use App\Support\Database\DbManager;
use App\Support\Redis\RedisManager;
use \Exception;

class CdkLogic
{
    public function insertCdk()
    {
        //假设活动时间实在12-15 至 1-15
        $day = 0;
        $data = [];
        $startTime = strtotime('2020-12-15');
        for ($i = 31; $i <= 60; $i++) {
            $time = $startTime + ($day * 86400);
            for ($j = 2001; $j <= 3000; $j++) {
                array_push(
                    $data,
                    [
                        'cdk' => uniqid($i . $j),
                        'time' => $time
                    ]
                );
            }

            $day++;
        }


        DbManager::getInstance()->insertAll('cdk', $data);
    }


    public function getCdk()
    {
        $user = AuthManager::getPayload();
        $time = $_SERVER['REQUEST_TIME'];

        $redis = RedisManager::getInstance();
        $getCdkBeingRedisKey = 'getCdkBeing:'.$user['userid'];
        try {
            if ($redis->incr($getCdkBeingRedisKey) > 1) {
                throw new Exception('操作太频繁，休息一下吧');
            }

            $db = DbManager::getInstance();
            //判断资格是单用户并发
            $selfMsg = $db->getCount('msg', '1', 'userid=' . $user['userid']);

            $likeCount = $db->getCount('like_msg', '1', 'userid=' . $user['userid']);
            if ($selfMsg != 1 || $likeCount < BusinessLogic::$activity['get_cdk_like_count']) {
                throw new Exception('你没有领取资格');
            }

            //是否领取过
            #####万一redis崩掉，不至于超领
            $exists = $db->getCount('cdk', '1', "userid={$user['userid']}");
            if ($exists) {
                throw new Exception('已经领取过了');
            }

            $res = $db->update(
                'cdk',
                ['userid' => $user['userid']],
                "userid is null and time <= {$time} limit 1"
            );

            if ($res === 0) {
                throw new Exception('CDK已被抢光');
            }

            $cdkRow = $db->first("select cdk from cdk where userid={$user['userid']}");

            $redis->expire($getCdkBeingRedisKey, 1);
            return [ErrCode::$successCode, ['cdk' => $cdkRow['cdk'] ?? ''], '领取成功'];
        } catch (\Throwable $e) {
            $redis->expire($getCdkBeingRedisKey, 1);
            return [ErrCode::$failCode, [], $e->getMessage()];
        }
    }


    public function myCdk()
    {
        $user = AuthManager::getPayload();
        if (empty($user)) {
            return [ErrCode::$failCode, [], '请先登录'];
        }

        $db = DbManager::getInstance();
        $cdkRow = $db->first("select cdk from cdk where userid={$user['userid']}");
        $cdk = $cdkRow ? $cdkRow['cdk'] : '';
        return [ErrCode::$successCode, ['cdk' => $cdk], ''];
    }
}